<?php

namespace Biz\model\brand;

use Biz\cache\brand\Brand as cBrand;
use Doraemon\pockets\datebase\BaseDbModel;
use Doraemon\tools\ImgUrl;

/**
 * Class Brand
 * @package Doraemon\model
 */
class Brand extends BaseDbModel
{

    const _CONFIG_FILE_ = 'db_store';

    const _CONFIG_SELECT_ = 'db_store';

    const _DATABASE_ = 'store';

    const _TABLE_NAME = 'brand';

    const _SUB_TABLE = false;

    // 状态为启用
    const STATUS_USING = 1;

    // 状态为被删除
    const STATUS_DELETE = 0;

    //wiki状态可见
    const WIKI_STATUS_VISIBLE = 1;
    //wiki状态不可见
    const WIKI_STATUS_INVISIBLE = 0;
    //推荐状态：推荐
    const SUGGEST_STATUS_NORMAL = 1;
    //推荐状态：不推荐
    const SUGGEST_STATUS_NOT = 0;
    //推荐状态：优先推荐
    const SUGGEST_STATUS_PRIORITY = 3;
    //推荐状态：降级推荐
    const SUGGEST_STATUS_DOWNGRADE = 4;

    const TYPE_BRAND = 1;
    const TYPE_SHOP = 2;

    // 品牌子身份（0：待定；1：到期品牌；2：普通认证品牌；3：精选品牌；4：超级品牌）
    const BRAND_TYPE_DEFAULT = 0;
    const BRAND_TYPE_EXPIRE = 1;
    const BRAND_TYPE_COMMON = 2;
    const BRAND_TYPE_BEST = 3;
    const BRAND_TYPE_SUPER = 4;

    const BRAND_TYPE = [
        self::BRAND_TYPE_DEFAULT => '待定',
        self::BRAND_TYPE_EXPIRE => '到期品牌',
        self::BRAND_TYPE_COMMON => '普通认证品牌',
        self::BRAND_TYPE_BEST => '精选品牌',
        self::BRAND_TYPE_SUPER => '超级品牌',
    ];

    const ADM_BRAND_TYPE = [
        self::BRAND_TYPE_COMMON => '普通认证品牌',
        //付费品牌
        self::BRAND_TYPE_BEST => '精选品牌',
        self::BRAND_TYPE_SUPER => '超级品牌',
    ];

    const TOLL_BRAND_TYPE = [
        //付费品牌
        self::BRAND_TYPE_BEST,
        self::BRAND_TYPE_SUPER,
    ];

    const SEARCH_BRAND_TYPE = [
        1 => '品牌名称',
        2 => '品牌别称',
        3 => '内容检索词',
    ];

    public static function incrGrowth($id, $growth, $level = 0): int
    {
        $data = ['growth_value[+]' => $growth];
        if ($level > 0) $data['level'] = $level;
        return self::update($data, ['id' => $id])->rowCount();
    }

    public static function getBrandIdsBySuggestStatus($suggestStatus)
    {
        return self::select("id", [
            "AND" => [
                'status' => self::STATUS_USING,
                'suggest_status' => $suggestStatus,
            ],
        ]);
    }

    public static function getBrandIdsByStoreStatus($storeStatus)
    {
        return self::select("id", [
            "AND" => [
                'status' => self::STATUS_USING,
                'store_status' => $storeStatus,
            ],
        ]);
    }

    public static function addBrand($data)
    {
        $data['status'] = self::STATUS_USING;
        $data['updated_time'] = date("Y-m-d H:i:s", time());
        $data['created_time'] = date("Y-m-d H:i:s", time());
        if (self::insert($data)) {
            return self::id();
        }
    }

    public static function getAllBrand()
    {
        return self::select("*", [
            "AND" => ['status' => self::STATUS_USING],
            "ORDER" => 'sort',
        ]);
    }

    public static function filterBrandIdsByWiki($brandIds)
    {
        return self::select("id", [
            "AND" => [
                'id' => $brandIds,
                'wiki_status' => self::WIKI_STATUS_VISIBLE,
                'status' => self::STATUS_USING,
            ],
        ]);
    }

    public static function getBrand($brandWhere = [], $order = [], $limit = [])
    {
        $where = [];
        if (!isset($brandWhere['status'])) {
            $where['AND']['status'] = self::STATUS_USING;
        } else {
            $where['AND']['status'] = $brandWhere['status'];
        }
        if (isset($brandWhere['uid']) && $brandWhere['uid']) {
            $where['AND']['uid'] = $brandWhere['uid'];
        }
        if (isset($brandWhere['brandIds']) && $brandWhere['brandIds']) {
            $where['AND']['id'] = $brandWhere['brandIds'];
        }
        if (isset($brandWhere['type'])) {
            $where['AND']['type'] = $brandWhere['type'];
        }
        if (isset($brandWhere['brand_type'])) {
            $where['AND']['brand_type'] = $brandWhere['brand_type'];
        }
        if (isset($brandWhere['wikiStatus'])) {
            $where['AND']['wiki_status'] = $brandWhere['wikiStatus'];
        }
        if (isset($brandWhere['storeStatus'])) {
            $where['AND']['store_status'] = $brandWhere['storeStatus'];
        }
        if (isset($brandWhere['suggestStatus'])) {
            $where['AND']['suggest_status'] = $brandWhere['suggestStatus'];
        }
        if (isset($brandWhere['pack_type'])) {
            $where['AND']['pack_type'] = $brandWhere['pack_type'];
        }
        if (isset($brandWhere['is_test'])) {
            $where['AND']['is_test'] = $brandWhere['is_test'];
        }
        if (isset($brandWhere['brandName']) && $brandWhere['brandName']) {
            $where['AND']['OR #brandName'] = [
                'brand_name[~]' => $brandWhere['brandName'],
                'en_brand_name[~]' => $brandWhere['brandName'],
            ];
        }
        if ($limit) {
            $where['LIMIT'] = $limit;
        }

        return self::select("*", $where);
    }

    public static function getBrandByFilter($where, $field = '*')
    {
        $where['status'] = self::STATUS_USING;
        $result = self::select($field, $where);

        return $result;
    }

    public static function getBrandCountByWhere($brandWhere = [])
    {
        $where = [];
        if (!isset($brandWhere['status'])) {
            $where['AND']['status'] = self::STATUS_USING;
        } else {
            $where['AND']['status'] = $brandWhere['status'];
        }
        if (isset($brandWhere['brandIds']) && $brandWhere['brandIds']) {
            $where['AND']['id'] = $brandWhere['brandIds'];
        }
        if (isset($brandWhere['type'])) {
            $where['AND']['type'] = $brandWhere['type'];
        }
        if (isset($brandWhere['brand_type'])) {
            $where['AND']['brand_type'] = $brandWhere['brand_type'];
        }
        if (isset($brandWhere['wikiStatus'])) {
            $where['AND']['wiki_status'] = $brandWhere['wikiStatus'];
        }
        if (isset($brandWhere['storeStatus'])) {
            $where['AND']['store_status'] = $brandWhere['storeStatus'];
        }
        if (isset($brandWhere['suggestStatus'])) {
            $where['AND']['suggest_status'] = $brandWhere['suggestStatus'];
        }
        if (isset($brandWhere['pack_type'])) {
            $where['AND']['pack_type'] = $brandWhere['pack_type'];
        }
        if (isset($brandWhere['is_test'])) {
            $where['AND']['is_test'] = $brandWhere['is_test'];
        }
        if (isset($brandWhere['uid'])) {
            $where['AND']['uid'] = $brandWhere['uid'];
        }
        if (isset($brandWhere['brandName']) && $brandWhere['brandName']) {
            $where['AND']['OR #brandName'] = [
                'brand_name[~]' => $brandWhere['brandName'],
                'en_brand_name[~]' => $brandWhere['brandName'],
            ];
        }

        return self::count($where);
    }

    public static function getBrandListByIds($ids, $field = "*")
    {
        $brandList = self::select($field, [
            "AND" => [
                "status" => self::STATUS_USING,
                "id" => $ids,
            ],
            "ORDER" => [
                'brand_name' => "ASC",
            ],
        ]);
        $formatData = [];
        foreach ($brandList as $brand) {
            $formatData[$brand["id"]] = $brand;
        }

        return $formatData;
    }

    public static function getBrandByIds($order, $limit, $ids)
    {
        $data['status'] = self::STATUS_USING;
        $data['id'] = $ids;

        return self::select("*", [
                "AND" => $data,
                "ORDER" => [
                    $order['order'] => $order['sort'],
                ],
                "LIMIT" => $limit,
            ]
        );
    }

    /** 根据标签id获取品牌信息
     * @param $tagIds
     * @return mixed
     */
    public static function getBrandByTagIds($tagIds)
    {

        $data['status'] = self::STATUS_USING;
        $data['tag_id'] = $tagIds;

        return self::select("*", [
                "AND" => $data,
            ]
        );
    }

    public static function updateBrandInfoById($id, $data)
    {
        $data['updated_time'] = date("Y-m-d H:i:s", time());
        $result = self::update($data, [
            "id" => $id,
        ]);
        cBrand::mDelItems($id);

        return $result;
    }

    public static function getBrandUidById($id)
    {
        return self::get("uid", [
            "AND" => [
                'id' => $id,
                "status" => self::STATUS_USING,
            ],
        ]);
    }

    public static function getBrandUidsByIds($ids)
    {
        return self::select("uid", [
            "AND" => [
                'id' => $ids,
                "status" => self::STATUS_USING,
            ],
        ]);
    }

    public static function getBrandInfoById($id)
    {
        return self::get("*", [
            "AND" => [
                'id' => $id,
                "status" => self::STATUS_USING,
            ],
        ]);
    }

    public static function getInfo($id)
    {
        return self::get("*", [
            "AND" => [
                'id' => $id,
            ],
        ]);
    }

    public static function getInfoByIds($ids)
    {
        return self::select("*", [
            "AND" => [
                'id' => $ids,
            ],
        ]);
    }

    public static function getBrandIdByUid($uid)
    {
        return self::get("id", [
            "AND" => [
                'uid' => $uid,
            ],
        ]);
    }

    public static function getNormalBrandByUid($uid)
    {
        return self::get("*", [
            "AND" => [
                'uid' => $uid,
                "status" => self::STATUS_USING,
            ],
        ]);
    }

    public static function selectNormalBrandsByUid($uid)
    {
        return self::select("*", [
            "AND" => [
                'uid' => $uid,
                "status" => self::STATUS_USING,
            ],
        ]);
    }

    public static function getBrandInfoByUid($uid)
    {
        return self::get("*", [
            "AND" => [
                'uid' => $uid,
            ],
        ]);
    }


    /** 根据标签id获取品牌信息
     * @param $tagIds
     * @return mixed
     */
    public static function getBrandByTagIds_2($tagIds)
    {
        $data['status'] = self::STATUS_USING;
        $data['tag_id'] = $tagIds;

        return self::select("*", [
                "AND" => $data,
                'SORT' => ['brand_type' => 'desc'],
            ]
        );
    }

    /**
     * @param $ids
     * @param false $is_order
     * @return array
     */
    public static function getUidsByIds($ids, bool $is_order = false): array
    {
        $rs = [];
        $where['id'] = $ids;
        $where['status'] = self::STATUS_USING;

        if ($is_order) {
            $where['ORDER'] = ['id' => $ids];

        }
        $list = self::select(['id', 'uid'], $where);
        if ($list && is_array($list)) {
            foreach ($list as $value) {
                $rs[$value['id']] = $value['uid'];
            }
        }

        return $rs;
    }

    public static function getBrandIdByName($brand_name = '')
    {
        return self::get('id', [
            'brand_name' => $brand_name,
            'status' => self::STATUS_USING,
        ]);
    }

    public static function getPaidBrandInfosByIds($ids)
    {
        return self::select("*", [
            "AND" => [
                'id' => $ids,
                "status" => self::STATUS_USING,
                "brand_type" => [
                    self::BRAND_TYPE_BEST,
                    self::BRAND_TYPE_SUPER,
                ],
            ],
        ]);
    }

    public static function getByWhere($where, $field = '*')
    {
        $brandInfo = self::get($field, $where);
        if ($brandInfo) {
            self::formatBrandField($brandInfo);
        }

        return $brandInfo;
    }

    public static function selectByWhere($where, $field = '*')
    {
        $brandList = self::select($field, $where);
        if ($brandList) {
            foreach ($brandList as &$brand) {
                self::formatBrandField($brand);
            }
        }

        return $brandList;
    }

    private static function formatBrandField(&$brand)
    {
        $brand['logo_url'] = isset($brand['logo']) ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brand['logo'],
            ImgUrl::IMAGE_SIZE_SQ_PHONE) : \Biz\service\brand\Brand::BRAND_DEFAULT_LOGO;
    }

    /**
     * 获取所有品牌的指定字段信息
     * @param string $field
     * @return array|bool
     */
    public static function getAllBrandInfo($field = '*')
    {
        return self::select($field, [
            "AND" => ['status' => self::STATUS_USING],
            "ORDER" => 'sort',
        ]);
    }

    /**
     * 获取所有uid>0的品牌
     * @return array|bool
     */
    public static function getAllBrandForRecommend()
    {
        $where ['status'] = self::STATUS_USING;
        $where ['uid[>]'] = 0;
        $where ['ORDER'] = 'sort';

        return self::select("*", $where);
    }

    /**
     * @param array $brandWhere
     * @return bool|int|mixed|string
     */
    public static function getCountByWhere(array $brandWhere = [])
    {
        return self::count($brandWhere);
    }

    //查询状态为正常的 并且是高级pro套餐的品牌数据 限制12条
    public static function getPackTypePro(): array
    {
        $where ['status'] = self::STATUS_USING;
        $where ['uid[>]'] = 0;
        $where ['pack_type'] = BrandPackage::PACK_HIGH_CERTIFIED_PLUS;
        $where ['LIMIT'] = 12;

        return array_column(self::select("*", $where), 'id');
    }

    /**
     * 获取过期品牌uid
     * @return array
     */
    public static function getOverBrandsUids(): array
    {
        $where['status'] = Brand::STATUS_DELETE;
        $where['brand_type'] = Brand::BRAND_TYPE_EXPIRE;
        $where['uid[>]'] = 0;
        return Brand::select('uid', $where) ?? [];
    }

    /**
     * 查询uids是否是品牌uids
     * @param $uids
     * @return array|bool
     */
    public static function getUidsByUids($uids)
    {
        $where['status'] = Brand::STATUS_USING;
        $where['brand_type[>]'] = Brand::BRAND_TYPE_EXPIRE;
        $where['uid'] = $uids;
        return Brand::select('uid', $where) ?: [];
    }

}

